package com.mysteel.monitor.core.model;

import lombok.Data;

import java.lang.management.MemoryUsage;
import java.text.DecimalFormat;

/**
 *  内存使用信息
 * @author Administrator
 */
@Data
public class MemoryUsageInfo {
    String heapType;
    String name;
    long used;
    long total;
    long max;
    /** 使用率 **/
    long useage;

    String usedStr;
    String totalStr;
    String maxStr;

    int unit;
    String unitStr;

    public MemoryUsageInfo(String heapType,String name, long used, long total, long max) {
        this.heapType = heapType;
        this.name = name;
        this.used = used;
        this.total = total;
        this.max = max;
        this.usedStr = FormetFileSize(used);
        this.totalStr = FormetFileSize(total);
        this.maxStr = FormetFileSize(max);
        unitStr = "K";
        unit = 1024;
        if (used / 1024 / 1024 > 0) {
            unitStr = "M";
            unit = 1024 * 1024;
        }
    }

    /**
     *  内存信息
     * @param heapType
     * @param name
     * @param usage
     */
    public MemoryUsageInfo(String heapType,String name, MemoryUsage usage) {
        this(heapType,name, usage.getUsed(), usage.getCommitted(), usage.getMax());
    }

    private String format(long value) {
        String valueStr = "-";
        if (value == -1) {
            return "-1";
        }
        if (value != Long.MIN_VALUE) {
            valueStr = value / unit + unitStr;
        }
        return valueStr;
    }

    public String FormetFileSize(long fileS) {//转换文件大小
        DecimalFormat df = new DecimalFormat("#.00");
        String fileSizeString = "";
        if (fileS < 1024) {
            fileSizeString = df.format((double) fileS) + "B";
        } else if (fileS < 1048576) {
            fileSizeString = df.format((double) fileS / 1024) + "K";
        } else if (fileS < 1073741824) {
            fileSizeString = df.format((double) fileS / 1048576) + "M";
        } else {
            fileSizeString = df.format((double) fileS / 1073741824) + "G";
        }
        return fileSizeString;
    }
}
